package top.jnaw.jee.platform.controller.basics.extend;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import top.jnaw.jee.platform.Consts;
import top.jnaw.jee.platform.Consts.Result;
import top.jnaw.jee.platform.model.Mediation;
import top.jnaw.jee.platform.model.Users;
import top.jnaw.jee.utils.ModelResult;
import top.jnaw.jee.utils.Shiros;
import top.jnaw.jee.utils.Strings;
import top.jnaw.jee.utils.wechat.Wechats;

public class ApprovalMediationController extends Controller {

  private static final String WECHAT_STATE = "mediation";
  private static final String WECHAT_APP_URL =
      Consts.DOMAIN + "wechat/index.html?data=%s";

  public void index() {

    Wechats.redirect(this, WECHAT_STATE, WECHAT_APP_URL);
  }

  public void add() {
    ModelResult result = new ModelResult(Result.kBadParam);
    JSONObject req = Strings.toJSONObject(this);
    final String openid = Strings.getString(req, "openid", "");
    final String request = Strings.getString(req, "req", "");
    final String process = Strings.getString(req, "process", "");
    final String require = Strings.getString(req, "require", "");
    final JSONArray person = Strings.getJSONArray(req, "person", null);
    final JSONArray accessory = Strings.getJSONArray(req, "accessory", null);
    if (StrKit.notBlank(openid)) {
      result = Mediation
          .add(openid, request, process, require, person, accessory);
    }
    renderJson(result.toJson());
  }

  public void list() {
    JSONObject req = Strings.toJSONObject(this);
    final int page = Strings.getInt(req, "page", Consts.DEFAULT_PAGE);
    final int size = Strings.getInt(req, "size", Consts.DEFAULT_PAGE_SIZE);
    final JSONArray filter = Strings.getJSONArray(req, "filter", null);
    Users user = Users.getByUsername(Shiros.getUser());
    int uid = (null != user) ? user.getId() : -1;
    renderJson(Strings
        .formatJsonDateTime(
            Strings.formatPage(Mediation.list(page, size, filter, uid))));
  }

  public void query() {
    ModelResult result = new ModelResult(Result.kBadParam);
    JSONObject req = Strings.toJSONObject(this);
    final int id = Strings.getInt(req, "id", Consts.DEFAULT_BAD_ID);
    if (id > 0) {
      result = Mediation.query(id);
    }
    renderJson(result.toJson());
  }
}
